﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net.Http;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Properties;
using System.ServiceModel.Channels;

namespace BartonExtension
{
    public static class NetworkingExtensions
    {
        public static string GetClientIp(HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            }
            else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
            {
                RemoteEndpointMessageProperty prop;
                prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
                return prop.Address;
            }
            else
            {
                return null;
            }
        }

        public static uint EncodeIPToLong(string ip)
        {
            /*string ip_1 = int.Parse(ip.Split('.')[0].ToString()).ToString("000");
            string ip_2 = int.Parse(ip.Split('.')[1].ToString()).ToString("000");
            string ip_3 = int.Parse(ip.Split('.')[2].ToString()).ToString("000");
            string ip_4 = int.Parse(ip.Split('.')[3].ToString()).ToString("000");
            string longFormat = ip_1 + ip_2 + ip_3 + ip_4;
            return longFormat;*/
            var xl = System.Net.IPAddress.Parse(ip);
            return BitConverter.ToUInt32(xl.GetAddressBytes(), 0);
        }

        public static string DecodeIPToLong(uint ip)
        {
            /*string ip_ = ip.ToString();
            string ip_1 = ip_.Substring(0, 3).toInt32().Value.ToString();
            string ip_2 = ip_.Substring(3, 3).toInt32().Value.ToString();
            string ip_3 = ip_.Substring(6, 3).toInt32().Value.ToString();
            string ip_4 = ip_.Substring(9, 3).toInt32().Value.ToString();

            return ip_1 + "." + ip_2 + "." + ip_3 + "." + ip_4;*/
            byte[] ipBytes = BitConverter.GetBytes(ip);
            System.Net.IPAddress ip_ = new System.Net.IPAddress(ipBytes);
            return ip_.ToString();
        }

        public static string GetValueFromUrlWithParameter(this string url,string parameter)
        {
            string theVal = "";
            string parametersStr = url.Substring(url.LastIndexOf('?') + 1);
            string[] parameters = parametersStr.Split('&');
            foreach(string param in parameters)
            {
                string key = param.Split('=')[0];
                string value = param.Split('=')[1];
                if (key.Equals(parameter))
                {
                    theVal = value;
                }
            }
            return theVal;
        }
    }
}
